package com.example.mythealthapp.users

import android.content.ContentValues
import android.content.Intent
import android.os.Bundle
import android.text.Editable
import android.text.TextWatcher
import android.util.Log
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.example.mythealthapp.HomeMenuActivity
import com.example.mythealthapp.R
import kotlinx.android.synthetic.main.activity_login.*


class LoginActivity : AppCompatActivity() {

    private val helper: DBHelper = DBHelper(this, "User", 1)

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_login)

        val userInputWatcher = object : TextWatcher {
            override fun beforeTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                Log.i(ContentValues.TAG,"beforeTextChanged:$p0")
            }

            override fun onTextChanged(p0: CharSequence?, p1: Int, p2: Int, p3: Int) {
                Log.i(ContentValues.TAG,"onTextChanged:$p0")
            }

            override fun afterTextChanged(p0: Editable?) {
                Log.i(ContentValues.TAG,"afterTextChanged:$p0")
            }

        }

        login_EditText_userphone.addTextChangedListener(userInputWatcher)
        login_EditText_pass.addTextChangedListener(userInputWatcher)

        login_button_register.setOnClickListener {
            val intent= Intent(this,RegisterActivity::class.java)
            startActivity(intent)
            finish()
        }
        login_button_login.setOnClickListener {
            val userphone=login_EditText_userphone.text.toString()
            val pass=login_EditText_pass.text.toString()
            if(tologin(userphone,pass)) {
                val intent = Intent(this, HomeMenuActivity::class.java)
                intent.putExtra("userphone",userphone)
                startActivity(intent)
                finish()
            }else{
                Toast.makeText(this,"密码错误", Toast.LENGTH_LONG).show()
            }
        }
    }
    private fun tologin(userphone: String, pass: String): Boolean {
        val db=helper.readableDatabase
        val cursor = db.rawQuery("select * from ${User.TABLE} where ${User.U_phone}=? and ${User.U_pass} = ?",
            arrayOf(userphone,pass))
        if(cursor.moveToFirst()){return true}
        return false
    }
}